package com.gujiangbo.lru;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @Author: gujiangbo.co
 * @Contact: 646832012@qq.com
 * @Date: 2022/3/19 15:50
 * @Version: 1.0
 * @Description:
 */
public class LRUCacheDemo<K, V> extends LinkedHashMap<K, V> {

    private int capacity;//LRU缓存

    public LRUCacheDemo(int capacity) {
        super(capacity, 0.75f, true);
        this.capacity = capacity;
    }

    /**
     * 重写 删除 最早的节点的条件
     *
     * @param eldest
     * @return
     */
    @Override
    protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        return super.size() > capacity;
    }


    public static void main(String[] args) {
        LRUCacheDemo lruCacheDemo = new LRUCacheDemo(3);

        lruCacheDemo.put(1, "a");
        lruCacheDemo.put(2, "b");
        lruCacheDemo.put(3, "c");
        System.out.println(lruCacheDemo.keySet());
        lruCacheDemo.put(4, "d");
        System.out.println(lruCacheDemo.keySet());
        lruCacheDemo.put(5, "e");
        System.out.println(lruCacheDemo.keySet());
    }
}
